<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button :disabled="!canSave" @click="saveAndSubmit()" v-if="!orderId && $permission('withTableRecordOrder:saveAndSubmit')">保存并提交</el-button>
        <el-button :disabled="!canSave" @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-supplierName>
              <el-input
                v-model="formInfo.data.supplierName"
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择供应商"
              >
                <template #append>
                  <el-icon @click="_selectsupplier"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品
              </el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品
              </el-button>
            </template>
            <template v-slot:filter-scanCode>
              <div class="scan-input-box">
                <ScanInputBox
                  :table-data="tableInfo.data"
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  :disabled="!canAddProduct"
                  @callback="onCallBackScanData"
                />
              </div>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                row-key="rowId"
                :checkbox="true"
                :isRowClickSelect="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-batchNumber="scope">
                  <el-input
                    v-model="scope.row.batchNumber"
                    :maxlength="25"
                    @change="changeData($event, scope.row, scope.$index)"
                    @input="(e) => (scope.row.batchNumber = validSe(e))"
                  />
                  <!-- <p v-else>
                    {{ scope.row.batchNumber || '-' }}
                  </p> -->
                </template>
                <template v-slot:col-productionDate="scope">
                  <el-date-picker
                    v-model="scope.row.productionDate"
                    value-format="YYYY-MM-DD"
                    :disabled-date="productionTimePickerOptions.disabledDate"
                    @change="changeData($event, scope.row, scope.$index)"
                  />
                  <!-- <p v-else>
                    {{ scope.row.productionDate || '-' }}
                  </p> -->
                </template>
                <template v-slot:col-validityDate="scope">
                  <el-date-picker
                    v-model="scope.row.validityDate"
                    value-format="YYYY-MM-DD"
                    :disabled-date="validityTimePickerOptions.disabledDate"
                    @change="changeData($event, scope.row, scope.$index)"
                  />
                  <!-- <p v-else>
                    {{ scope.row.validityDate || '-' }}
                  </p> -->
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    v-if="scope.row.qtyOperateMode !== 3"
                    class="margin-bottom"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item>
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                              @change="changeSmall($event, scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}[price]`"
                    :rules="
                      scope.$index >= 0
                        ? {
                            validator: $validate.positiveMoney,
                            trigger: 'blur',
                          }
                        : {}
                    "
                  >
                    <el-input-number
                      v-model="scope.row.price"
                      controls-position="right"
                      style="minwidth: 100px; margintop: 18px"
                      :precision="systemConfig.price_precision"
                      :step="1"
                      :min="0"
                      :max="999999999999999"
                      @change="
                        changePrice($event, `data.${scope.$index}.price`)
                      "
                    />
                    <p
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.price > scope.row.purchaseLimitPrice
                      "
                      style="color: red"
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!--选择产品-->
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query.queryMap"
      :api="productInfo.api"
      :query-params="productInfo.query.queryParams"
      :notDefaultProductSupplier="false"
      :table-key="productInfo.tableKey"
      :show-price="$permission('withTableRecordOrder:price')"
      @callback="selectProduct"
    />
    <!--选择供应商-->
    <select-supplier
      v-if="selectSupplierInfo.visible"
      v-model:show-dialog="selectSupplierInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :api="selectSupplierInfo.api"
      :query="selectSupplierInfo.query"
      @callback="selectSupplierCallback"
    />
  </div>
</template>

<script setup name="withTableRecordOrderModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'

import {
  getWithTableRecordOrderById,
  getWithTableRecordOrderDetailAll,
  createWithTableRecordOrder,
  createWithTableRecordOrderAndSave,
  updateWithTableRecordOrder,
  withTableRecordOrderBatchValidate,
  getWithTableRecordOrderDetailScan,
} from '@/api/withTable.js'
import {
  getSupplierPage,
  getCustomizeListWithAllSupplierList,
} from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import ScanInputBox from '../components/ScanInputBox'
import SelectSupplier from '@/components/SelectSupplier/index'
import _ from 'lodash'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
let pickerOptions = {
  disabledDate(time) {
    return time.getTime() > Date.now() // 选当前时间之后的时间
    // return time.getTime() > Date.now() // 选当前时间之前的时间
  },
}

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const NewSelectProduct = defineAsyncComponent(() =>
  import('@/components/NewSelectProduct/index')
)
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps(['visible', 'title', 'orderId'])

const btnLoading = ref(true)
const formRefs = ref('')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const productionTimePickerOptions = reactive({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = reactive({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})

const scanInfo = reactive({
  api: getWithTableRecordOrderDetailScan,
  query: {
    supplierId: '',
    saleId: props.orderId,
  },
})
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    supplierName: '',
    supplierId: '',
  },
  fieldList: [
    {
      label: '手术名称',
      value: 'surgeryName',
      type: 'input',
    },

    {
      label: '手术时间',
      value: 'surgeryTime',
      type: 'date',
      dateType: 'datetime',
      TimePickerOptions: pickerOptions,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    {
      label: '手术地点',
      value: 'surgeryPlace',
      type: 'input',
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    surgeryName: [
      { required: true, message: '请输入手术名称', trigger: 'blur' },
    ],
    surgeryPlace: [
      { required: false, message: '请输入手术地点', trigger: 'blur' },
    ],
    surgeryTime: [
      { required: true, message: '请选择手术时间', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'scanCode' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '复制行',
        event: addBatchNumber,
        show: true,
        ifRender: function (row) {
          return row.codeType !== 3
        },
      },
      {
        label: '删除产品',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
let productInfo = reactive({
  visible: false,
  api: getCustomizeListWithAllSupplierList,
  tableKey:
    'withTableRecordOrderProductPage-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      withOperateTable: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
    },
    queryParams: {
      codeType: 3,
    },
  },
})

const selectSupplierInfo = reactive({
  visible: false,
  index: '',
  api: getSupplierPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.data.length
})
const canAddProduct = computed(() => {
  return formInfo.data.supplierId
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(calcQty, parseFloat(row.price)),
        unitConvertCoefficient
      )
    })
  },
  {
    deep: true,
  }
)

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    hidden: true,
  },
  productionDate: {
    label: '生成日期',
    value: 'productionDate',
    type: 'slot',
    minWidth: '160px',
    hidden: true,
  },
  validityDate: {
    label: '失效日期',
    value: 'validityDate',
    minWidth: '160px',
    type: 'slot',
    hidden: true,
  },
  batchNumber: {
    label: '批号',
    value: 'batchNumber',
    type: 'slot',
    hidden: true,
  },
  defaultSupplierName: {
    label: '默认供应商',
    value: 'defaultSupplierName',
    type: 'column',
    hidden: true,
  },
  defaultSupplierCode: {
    label: '默认供应商编码',
    value: 'defaultSupplierCode',
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
if (!props.orderId) {
  formInfo.fieldList = formInfo.fieldList.filter(
    (item) => item.value !== 'orderNo'
  )
}

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
//数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
function largeMax(row) {
  //原厂码最大为1[0,1]
  if (row.codeType === 3) {
    return 1
  } else {
    return 99999999
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  if ((row.qtyOperateMode === 2 && row.stockQty > 0) || row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
    }
  }
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate(str)
  })
}
function changeSmall(e, row) {
  if (row.qtyOperateMode === 2) {
    if ((row.codeType === 2 && row.stockQty > 0) || row.codeType === 3) {
      if (e > 0) {
        row.largeUnitQty = 0
      }
    }
  }
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
function onCallBackScanData(stateProduct) {
  let itemIndex = tableInfo.data.findIndex((item) => {
    console.log(item._id)
    console.log(stateProduct.data._id)
    console.log(item._id === stateProduct.data._id)
    if (stateProduct.data.codeType === 3) {
      return (
        item.factoryMainCode === stateProduct.data.factoryMainCode &&
        item.factorySubCode === stateProduct.data.factorySubCode
      )
    } else {
      return item._id === stateProduct.data._id
    }
  })
  tableInfo.data.forEach((item) => {
    item.isChoice = false
  })
  if (itemIndex !== -1) {
    if (stateProduct.data.codeType === 3) {
      proxy.$message({
        message: '重复扫码',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    } else {
      tableInfo.data[itemIndex].calcQty = proxy.$fn.accAdd(
        stateProduct.data.calcQty || 1,
        tableInfo.data[itemIndex].calcQty || 0
      )
      tableInfo.data[itemIndex].largeUnitQty = parseInt(
        tableInfo.data[itemIndex].calcQty /
          tableInfo.data[itemIndex].unitConvertCoefficient
      )
      tableInfo.data[itemIndex].smallUnitQty = parseInt(
        tableInfo.data[itemIndex].calcQty %
          tableInfo.data[itemIndex].unitConvertCoefficient
      )
      tableInfo.data[itemIndex].isChoice = true
    }
  }
  if (stateProduct.data.codeType === 3 || itemIndex === -1) {
    if (stateProduct.data.qtyOperateMode === 2) {
      stateProduct.data.largeUnitQty = parseInt(
        stateProduct.data.calcQty / stateProduct.data.unitConvertCoefficient ||
          1
      )
      stateProduct.data.smallUnitQty = parseInt(
        stateProduct.data.calcQty % stateProduct.data.unitConvertCoefficient ||
          0
      )
    } else {
      stateProduct.data.largeUnitQty = stateProduct.data.calcQty || 1
      stateProduct.data.smallUnitQty = 0
    }
    stateProduct.data = {
      ...stateProduct.data,
      price: stateProduct.data.price || 0,
      isChoice: true,
      productionDate: stateProduct.data.productionDate || undefined,
      validityDate: stateProduct.data.validityDate || undefined,
    }
    tableInfo.data.unshift(stateProduct.data)
  }

  //let str = `data.0.largeUnitQty`
  //proxy.$refs.tableForm.clearValidate(str);
}
function getList() {
  getWithTableRecordOrderDetailAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      res.data.forEach((item) => {
        item.rowId = proxy.$fn.getUid()
      })
      tableInfo.data = generateProductKey(res.data)
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
    case 'changePrice':
      proxy.$refs.tableForm.clearValidate(data)
      break
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let notQtyDetails = tableInfo.data
      .filter((row) => !row.qty)
      .map((item) => item.productCode)
    if (notQtyDetails.length) {
      proxy.$message({
        message: `请填写产品编码为【${notQtyDetails}】的产品数量`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    //校验是否强制批号效期
    let details = generateProductKey(tableInfo.data)
    const needBatchNumberProduct = details
      .filter(
        (detail) =>
          detail.needBatchNumber === 1 &&
          ((!detail.batchNumber && detail.batchNumber !== 0) ||
            !detail.productionDate ||
            !detail.validityDate)
      )
      .map((detail) => detail.commonName)
    if (needBatchNumberProduct.length) {
      proxy.$alert(
        `请输入产品【${needBatchNumberProduct}】的批号效期`,
        '操作提示',
        {
          confirmButtonText: '确定',
        }
      )
      return
    }
    // 校验价格
    const noHavePriceProduct = details
      .filter((detail) => !detail.price && detail.price !== 0)
      .map((detail) => detail.commonName)
    if (noHavePriceProduct.length) {
      proxy.$alert(`请输入产品【${noHavePriceProduct}】的价格`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    //检验复制行或者新增不允许存在同产品同批号效期
    const _ids = details
      .filter((item) => item.codeType !== 3)
      .map((item) => item._id)
    const _idsSet = new Set(_ids)
    if (_idsSet.size !== _ids.length) {
      //获取重复的_id(key)并且去重
      const filterUnique = (arr) =>
        arr.filter((i) => arr.indexOf(i) !== arr.lastIndexOf(i))
      let arr = Array.from(new Set(filterUnique(_ids)))
      //重复数据
      let repeatDetails = []
      _.uniq(arr).forEach((item) => {
        repeatDetails.push(details.find((i) => i._id === item))
      })
      let repeatCommonNames = repeatDetails.map((item) => {
        if (arr.includes(item._id)) {
          return item.commonName
        }
      })
      proxy.$alert(
        `产品【${repeatCommonNames}】存在相同批号效期产品，请修改`,
        '操作提示',
        {
          confirmButtonText: '确定',
        }
      )
      return
    }
    let data = formInfo.data
    details.forEach((item) => {
      if (item.codeType !== 3) {
        item.factoryMainCode = ''
        item.factorySubCode = ''
        item.details?.forEach((el) => {
          el.factoryMainCode = ''
          el.factorySubCode = ''
        })
      }
    })
    data.mergeDetails = proxy.$fn.filterBlacklist(details)
    withTableRecordOrderBatchValidate(data).then((res) => {
      if (res && res.success) {
        const api = props.orderId
          ? updateWithTableRecordOrder
          : isSaveAndSubmit === true ? createWithTableRecordOrderAndSave : createWithTableRecordOrder
        api(data).then((resp) => {
          if (resp && resp.success) {
            showDialog.value = false
            emit('returnModify')
          }
        })
      }
    })
  })
}

//选择供应商
function _selectsupplier() {
  selectSupplierInfo.visible = true
  selectSupplierInfo.query.supplierIdNotIn = formInfo.data.supplierId
}
function selectSupplierCallback(data = undefined) {
  if (data && data.supplierId) {
    formInfo.data.supplierId = data.supplierId
    formInfo.data.supplierName = data.supplierName
    productInfo.query.queryMap.supplierId.value = data.supplierId
    scanInfo.query.supplierId = data.supplierId
    tableInfo.data = []
  } else {
    formInfo.data.supplierId = ''
    formInfo.data.supplierName = ''
    productInfo.query.queryMap.supplierId.value = ''
    scanInfo.query.supplierId = ''
    tableInfo.data = []
  }
}
//选择产品
function addProduct() {
  const productIds = tableInfo.data.map((item) => item.productId)
  productInfo.query.queryMap.id.value = productIds.toString()
  productInfo.visible = true
}
function selectProduct(rows = []) {
  if (rows.length) {
    rows = generateProductKey(rows)
    rows = rows.map((row) => {
      return {
        price: row.price || 0,
        largeUnitQty: 0,
        qty: 1,
        code: null,
        productionDate: undefined,
        validityDate: undefined,
        productId: row.id,
        rowId: proxy.$fn.getUid(),
        id: null,
        factoryMainCode: row.mainCode,
        factorySubCode: row.subCode,
        defaultSupplierId: row.supplierId,
        defaultSupplierName: row.supplierName,
        defaultSupplierCode: row.supplierCode,
        defaultSupplierPrice: row.price,
        groupConcatIds: row.id,
        ...row,
      }
    })
    tableInfo.data = rows.concat(tableInfo.data)
  }
}
function addBatchNumber(row) {
  const index = tableInfo.data.findIndex((item) => item === row)
  tableInfo.data.splice(index, 0, {
    ...row,
    id: null,
    rowId: proxy.$fn.getUid(),
    batchNumber: '',
    largeUnitQty: undefined,
    smallUnitQty: undefined,
    calcQty: undefined,
    qty: undefined,
    productionDate: undefined,
    validityDate: undefined,
  })
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice && (row.codeType === 3 || row.codeType === 2)) {
    return 'success-row'
  } else {
    return ''
  }
}
function changeData(evet, row, index) {
  //批号效期改变更新_id
  let item = tableInfo.data.filter((item, i) => i === index)
  const key =
    item.productId +
    '&' +
    item.batchNumber +
    '&' +
    item.validityDate +
    '&' +
    item.productionDate
  tableInfo.data[index] = {
    ...tableInfo.data[index],
    _id: key,
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'withTableRecordOrderModify-com.slip.spd.entity.vo.withtable.WithTableRecordOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      if (props.orderId) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getMain() {
  getWithTableRecordOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      productInfo.query.queryMap.supplierId.value = res.data.supplierId
      filterInfo.query.queryMap.orderId.value = props.orderId
      scanInfo.query.supplierId = res.data.supplierId
      setBusinessDate()
      getList()
    }
  })
}
</script>
